#include "servicedao_file_impl.h"
#include "department.h"
using namespace std;
using namespace MAN;
ServiceDaoFileImpl::ServiceDaoFileImpl()
{

}

//从数据存储读取部门及员工信息
void ServiceDaoFileImpl::load(vector<Department> &vec)
{
	
	FILE* frp= fopen("account/services.dat","rb");
	if(frp == NULL)
	{
		return ;
	}
	
	vector<Employee> vec_emp;
	
	while(1)
	{	
		Department man_tmp;
		Employee emp_tmp;
		vec_emp.clear();
	 	char name_buff[50] = {};
	 	int id = 0;
	 	int num_emp = 0;
	 	int ret = 0;

		ret = fread(name_buff,sizeof(name_buff),1,frp);
		if(ret <= 0)
		{
			break;
		}
		fread(&id,sizeof(int),1,frp);
		fread(&num_emp,sizeof(int),1,frp);
				
		for(int j = 0; j < num_emp ; j++)
		{
			fread(&emp_tmp,sizeof(Employee),1,frp);	
			vec_emp.push_back(emp_tmp);		
		}						
		
		Department d(name_buff,id,vec_emp);
		vec.push_back(d);		
	}

	return ;
}

//将部门及员工信息写入数据存储
void ServiceDaoFileImpl::save(vector<Department> &vec)
{
	
	FILE* frp= fopen("account/services.dat","w");
	if(frp == NULL)
	{
		perror("open");
		return ;
	}
	int len_emp = 0;

	for(unsigned int i =0; i < vec.size(); i++)
	{

		fwrite(&vec[i].m_strName,sizeof(vec[i].m_strName),1,frp);
		fwrite(&vec[i].m_nId,sizeof(vec[i].m_nId),1,frp);

		len_emp = vec[i].m_vecEmps.size();
		fwrite(&len_emp,sizeof(int),1,frp);
		
		for(unsigned int j =0; j < vec[i].m_vecEmps.size(); j++)
		{
			fwrite(&vec[i].m_vecEmps[j],sizeof(Employee),1,frp);
		}
	
	}
}

ServiceDaoFileImpl::~ServiceDaoFileImpl()
{
	
}